import requests
import os
import time
import datetime

class XiaofeixiangCloud(object):
    base_dir = './'
    type_dict = {'WVP':"W",'VIS':'VIS','IR1':"IR1",'3DS':"3D"}
    hour_list = ['00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23']
    headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36',}
    def __init__(self):
        self.url_left = 'http://www.avt7.com/CloudChart/CloudChart?charttype={}&chartname='
        self.img_name = 'FY2G_{}_{}_{}_{}_00_L_PJ1_{}.JPG'
    
    # 获取昨天的时间
    def get_yesterday(self):
        yesterday = datetime.datetime.today() + datetime.timedelta(-1)
        str_yesterday = datetime.datetime.strftime(yesterday, "%Y%m%d")
        year = str_yesterday[:4]
        month = str_yesterday[4:6]
        day = str_yesterday[6:]
        return year, month, day

    # 判断文件夹是否存在，不存在则创建
    def exist_dir(self, dir_path):
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
    
    # 下载昨天的云图
    def request_yestoday(self):
        # 遍历4种图
        year, month, day = self.get_yesterday()
        for type_key in self.type_dict:
            # 遍历24小时
            for hour in self.hour_list:
                temp_dir = year + '/' + type_key
                save_dir = os.path.join(self.base_dir, temp_dir)
                self.exist_dir(save_dir)
                save_file = self.img_name.format(year,month,day,hour,self.type_dict[type_key])
                save_filepath = os.path.join(save_dir, save_file)
                url = self.url_left.format(type_key) + save_file
                response = requests.get(url=url, headers = self.headers)
                self.file_write(file_path=save_filepath, content=response.content, mode='wb')

    # 创建json文件夹并返回文件夹目录
    def file_write(self, file_path, content, mode='a'):
        '''
        1. 作用:创建文件并把content的内容写入到文件file_path中
        2. 参数:
            file_path:文件路径
            content:文件写入的内容
            mode:文件读写的模式,默认为'w'
            encoding:文件编码,默认为'utf8'
        3. 返回值:None
        '''
        f = open(file=file_path, mode=mode)
        f.write(content)
        f.close()

if __name__ == '__main__':
    cloud = XiaofeixiangCloud()
    cloud.request_yestoday()